import 'dart:async';

import 'package:inmotion_pro/pages/mixin/protocol_mixin.dart';
import 'package:inmotion_pro/service/realtime_data_server/vehicle_realtime_data/vehicle_realtime_all_info.dart';
import 'package:inmotion_pro/service/realtime_data_server/vehicle_realtime_data/vehicle_realtime_error.dart';
import 'package:inmotion_pro/service/realtime_data_server/vehicle_realtime_data/vehicle_realtime_info.dart';
import 'package:inmotion_pro/service/realtime_data_server/vehicle_realtime_data/vehicle_realtime_status.dart';
import 'package:inmotion_pro/service/realtime_data_server/vehicle_realtime_data/vehicle_statistics_once.dart';
import 'package:inmotion_pro/service/realtime_data_server/vehicle_realtime_data/vehicle_statistics_total.dart';
import 'package:get/get.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:flutter/material.dart';

enum PollingTimerType {
  integratedRealtimeAll("integrated_realtime_all"), // 综合实时全部信息
  realtimeAll("all"), // 实时全部信息
  realtimeInfo("info"), // 实时信息
  realtimeStatus("status"), // 实时状态
  realtimeError("error"), // 实时错误
  realtimeBattery("battery"), // 实时电池信息
  realtimeSetting("setting"), // 实时设置信息
  realtimeStatisticsOnce("statistics_once"), // 实时统计一次数据
  realtimeStatisticsTotal("statistics_total"); // 实时统计总数据

  final String tag;
  const PollingTimerType(this.tag);
}

// 实时数据服务
class RealTimeDataService extends GetxService with ProtocolMixin {
  // 蓝牙服务
  static RealTimeDataService get to => Get.find();

  // 运行标志映射
  final Map<String, bool> _runningFlags = {};

  // 基于 Timer 的调度：每个 tag 对应一个 Timer
  final Map<String, Timer?> _timers = {};

  // 标记某个 tag 是否正在执行单次轮询（避免重叠）
  final Map<String, bool> _isExecuting = {};

  // 添加监听
  Future<bool> addListener() {
    _stopTimer();
    protocolMixinListenBluetoothNotifyStream((p0) {
      _parseIntegratedRealtimeInfo(p0);
    });
    // 设置蓝牙数据上报间隔为3，单位 100ms
    return protocolMixinSetPeriodicDataReportingInterval(10);
  }

  // 开始轮询实时信息
  Future<bool> startLoop(List<(PollingTimerType, int)> timerTypes) async {
    for (final type in timerTypes) {
      final tag = type.$1.tag;
      // 如果已经在运行并有活跃的 Timer，则跳过
      if (_runningFlags[tag] == true && _timers[tag] != null) {
        continue;
      }

      // 标记为将要运行并初始化执行状态
      _runningFlags[tag] = true;
      _isExecuting[tag] = false;

      // 取消旧的 Timer（如果有），然后立即触发一次执行
      try {
        _timers[tag]?.cancel();
      } catch (_) {}
      _timers[tag] = null;
      // 如果旧执行尚未完成，不要立即触发新执行，以避免与旧执行重叠
      if (_isExecuting[tag] == true) {
        // 安排短延迟后触发（防御性），由 _runOnce 内部再次检查是否能执行
        _timers[tag] = Timer(const Duration(milliseconds: 50), () {
          _timers[tag] = null;
          if (_runningFlags[tag] == true) {
            _runOnce(type.$1, type.$2);
          }
        });
      } else {
        // 立即触发一次执行（不等待）
        _runOnce(type.$1, type.$2);
      }
    }
    return true;
  }

  // 基于 Timer 的单次执行函数，完成后会在 runningFlags 为 true 时再次安排下一次
  Future<void> _runOnce(PollingTimerType type, int milliseconds) async {
    final tag = type.tag;
    if (_runningFlags[tag] != true) return;
    if (_isExecuting[tag] == true) return; // 防止重叠执行
    _isExecuting[tag] = true;
    try {
      switch (type) {
        case PollingTimerType.integratedRealtimeAll:
          await _getIntegratedRealtimeAll();
          break;
        case PollingTimerType.realtimeAll:
          await _getRealtimeAll();
          break;
        case PollingTimerType.realtimeInfo:
          await _getRealtimeInfo();
          break;
        case PollingTimerType.realtimeStatus:
          await _getRealtimeStatus();
          break;
        case PollingTimerType.realtimeError:
          await _getRealtimeError();
          break;
        case PollingTimerType.realtimeBattery:
          await _getRealtimeBattery();
          break;
        case PollingTimerType.realtimeSetting:
          await _getRealtimeSettings();
          break;
        case PollingTimerType.realtimeStatisticsOnce:
          await getRealtimeStatisticsOnce(startIndex: 0, count: 1);
          break;
        case PollingTimerType.realtimeStatisticsTotal:
          await _getRealtimeStatisticsTotal();
          break;
      }
    } catch (e) {
      debugPrint('runOnce[$tag] 异常: $e');
    } finally {
      _isExecuting[tag] = false;
      // 如果仍应继续运行，安排下一次
      if (_runningFlags[tag] == true) {
        try {
          _timers[tag]?.cancel();
        } catch (_) {}
        _timers[tag] = Timer(Duration(milliseconds: milliseconds), () {
          _timers[tag] = null;
          _runOnce(type, milliseconds);
        });
      } else {
        // 清理 timer
        try {
          _timers[tag]?.cancel();
        } catch (_) {}
        _timers.remove(tag);
      }
    }
  }

  // 以下为各类型数据获取方法（无定时器，只负责获取一次）
  Future<void> _getIntegratedRealtimeAll() async {
    if (!GlobalService.to.isForeground) return;
    try {
      Map<String, dynamic> integratedRealtimeInfo =
          await protocolMixinGetIntegratedRealtimeInfoAll();
      _parseIntegratedRealtimeInfo(integratedRealtimeInfo);
    } catch (e) {
      debugPrint("获取综合实时信息失败: $e");
    }
  }

  // 解析综合实时信息的map
  void _parseIntegratedRealtimeInfo(Map<String, dynamic> info) {
    GlobalService.to.realtimeInfo.value = VehicleRealtimeInfo.fromMap(info);
    GlobalService.to.realtimeStatus.value = VehicleRealtimeStatus.fromMap(info);
    GlobalService.to.realtimeError.value = VehicleRealtimeError.fromMap(info);
    GlobalService.to.realtimeStatisticsOnce.value =
        VehicleStatisticsOnce.fromMap(info);
    GlobalService.to.realtimeStatisticsTotal.value =
        VehicleStatisticsTotal.fromMap(info);
  }

  Future<void> _getRealtimeAll() async {
    if (!GlobalService.to.isForeground) return;
    try {
      VehicleRealtimeAllInfo realtimeAllInfo =
          await protocolMixinGetRealtimeAll();
      GlobalService.to.realtimeAllInfo.value = realtimeAllInfo;
      GlobalService.to.realtimeInfo.value = realtimeAllInfo.info;
      GlobalService.to.realtimeStatus.value = realtimeAllInfo.status;
      GlobalService.to.realtimeError.value = realtimeAllInfo.error;
    } catch (e) {
      debugPrint("获取全部实时信息失败: $e");
    }
  }

  Future<void> _getRealtimeInfo() async {
    if (!GlobalService.to.isForeground) return;
    try {
      GlobalService.to.realtimeInfo.value =
          await protocolMixinGetRealtimeInfo();
    } catch (e) {
      debugPrint("获取实时信息失败: $e");
    }
  }

  Future<void> _getRealtimeStatus() async {
    if (!GlobalService.to.isForeground) return;
    try {
      GlobalService.to.realtimeStatus.value =
          await protocolMixinGetRealtimeStatus();
    } catch (e) {
      debugPrint("获取实时状态失败: $e");
    }
  }

  Future<void> _getRealtimeError() async {
    if (!GlobalService.to.isForeground) return;
    try {
      GlobalService.to.realtimeError.value =
          await protocolMixinGetRealtimeError();
    } catch (e) {
      debugPrint("获取实时错误失败: $e");
    }
  }

  Future<void> _getRealtimeBattery() async {
    if (!GlobalService.to.isForeground) return;
    try {
      GlobalService.to.realtimeBattery.value =
          await protocolMixinGetRealtimeBatteryInfo();
    } catch (e) {
      debugPrint("获取实时电池信息失败: $e");
    }
  }

  Future<void> _getRealtimeSettings() async {
    if (!GlobalService.to.isForeground) return;
    try {
      GlobalService.to.realtimeSetting.value =
          await protocolMixinGetSettingsAll();
    } catch (e) {
      debugPrint("获取实时设置信息失败: $e");
    }
  }

  Future<VehicleStatisticsOnce?> getRealtimeStatisticsOnce({
    int? startIndex,
    int? count,
    bool toUpdateGlobal = true,
  }) async {
    if (count != null && count > 1) {
      // 保证蓝牙包数据的可靠性，目前先限制count只能为1或null
      throw Exception("count参数只能为1或null");
    }
    if (!GlobalService.to.isForeground) return null;
    try {
      VehicleStatisticsOnce statisticsOnce =
          await protocolMixinGetStatisticsOnce(
        startIndex: startIndex,
        count: count,
      );
      if (toUpdateGlobal) {
        if (!statisticsOnce.isValid) return null;
        // 更新全局状态
        GlobalService.to.realtimeStatisticsOnce.value = statisticsOnce;
      }
      return statisticsOnce;
    } catch (e) {
      debugPrint("获取实时统计一次数据失败: $e");
      return null;
    }
  }

  Future<void> _getRealtimeStatisticsTotal() async {
    if (!GlobalService.to.isForeground) return;
    try {
      VehicleStatisticsTotal total = await protocolMixinGetStatisticsTotal();
      if (!total.isValid) return;
      GlobalService.to.realtimeStatisticsTotal.value = total;
    } catch (e) {
      debugPrint("获取实时设置信息失败: $e");
    }
  }

  // 停止轮询实时信息
  Future<bool> stopLoop() {
    _stopTimer();
    return Future(() => true);
  }

  // 删除监听
  Future<bool> removeListener() {
    protocolMixinCancelListenBluetoothNotifyStream();
    return protocolMixinSetPeriodicDataReportingInterval(0);
  }

  // 销毁轮询实时信息
  void disposeTimer(String tag) {
    _runningFlags[tag] = false;
    try {
      _timers[tag]?.cancel();
    } catch (_) {}
    _timers.remove(tag);
    _isExecuting.remove(tag);
    _runningFlags.remove(tag);
  }

  // 停止所有轮询
  void _stopTimer() {
    // 将所有运行标志设置为 false
    for (final key in _runningFlags.keys.toList()) {
      _runningFlags[key] = false;
    }
    // 取消并清理所有 timers
    _timers.forEach((_, t) {
      try {
        t?.cancel();
      } catch (_) {}
    });
    _timers.clear();
    _isExecuting.clear();
    _runningFlags.clear();
  }
}
